#include <iostream>
#include <limits>

using std::cout;
using std::endl;
using std::cin;

class Complex{
public:
    Complex(double dreal=0.0,double dimag=0.0)
    : _dreal(dreal)
    , _dimag(dimag)
    {
        cout<<"构造函数"<<endl;
    }


    Complex(const Complex &rhs)
    : _dreal(rhs._dreal)
    , _dimag(rhs._dimag)
    {
        cout<<"拷贝构造"<<endl;
    }

    ~Complex(){
        cout<<"析构函数"<<endl;

    }

        friend std::ostream &operator<<(std::ostream &os,const Complex &rhs);
        friend std::istream &operator>>(std::istream &is,Complex &rhs);
        //因为是往rhs写，const删掉，加上&:w
    

    void print() const{
        if(_dreal==0 && 0==_dimag)
            cout<<0<<endl;
        else if (0==_dreal){
            if(_dimag<0)
                cout<<_dreal<<"+"<<'('<<_dimag<<')'<<"i"<<endl;
            else
                cout<<_dreal<<"+"<<_dimag<<"i"<<endl;
        }
        else if (0 ==_dimag)
            cout<<_dreal<<endl;
        else{
            if(_dimag<0)
                cout<<_dreal<<"+"<<'('<<_dimag<<')'<<"i"<<endl;
            else
                cout<<_dreal<<"+"<<_dimag<<"i"<<endl;
        }
    }

private:
    double _dreal;
    double _dimag;
};


std::ostream &operator<<(std::ostream &os,const Complex &rhs){
    cout<<"重载输出流函数"<<endl;
    if(rhs._dreal==0 && 0==rhs._dimag)
        os<<0<<endl;
    else if (0==rhs._dreal){
        if(rhs._dimag<0)
            os<<rhs._dreal<<"+"<<'('<<rhs._dimag<<')'<<"i"<<endl;
        else
            os<<rhs._dreal<<"+"<<rhs._dimag<<"i"<<endl;
    }
    else if (0 ==rhs._dimag)
        os<<rhs._dreal<<endl;
    else{
        if(rhs._dimag<0)
            os<<rhs._dreal<<"+"<<'('<<rhs._dimag<<')'<<"i"<<endl;
        else
            os<<rhs._dreal<<"+"<<rhs._dimag<<"i"<<endl;
    }

    return os;
}

void readDouble(std::istream &is, double &number){
    while(is >> number, !is.eof()){
        if(is.bad()){
            cout<<"stream is bad"<<endl;
            return;
        }
        else if(is.fail()){
            cin.clear();
            cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
            cout<<"pls input double data"<<endl;
        }
        else
            break;
    }
}

std::istream &operator>>(std::istream &is,Complex &rhs){
    cout<<"重载输入流函数"<<endl;
    readDouble(is,rhs._dreal);
    readDouble(is,rhs._dimag);
    //is >> rhs._dreal >> rhs._dimag;
    //这样如果输入hello，则会有错误，不够健全

    return is;
}

void test2(){

    Complex c(2,3);
    operator<<(operator<<(cout,"c="),c).operator<<(endl);


    cout<<endl<<endl;
    Complex c2;
    cin>>c2;
    cout<<"c2="<<c2<<endl;

    cout<<1<<endl;
}

int main()
{   
    test2();
    return 0;
}

